//
//  TheirWishListViewController.m
//  eGifr
//
//  Created by Phien Tram on 8/9/13.
//  Copyright (c) 2013 eGiftr. All rights reserved.
//

#import "TheirWishListViewController.h"
#import "TheirWishListDetailsViewController.h"
#import "AppDelegate.h"
#import "UserDefaultHelper.h"
#import "ServiceNameMapper.h"
#import "FriendInfo.h"
#import "FriendsByUserIdResult.h"
#import "UIImageView+WebCache.h"

@interface TheirWishListViewController ()
{
    NSInteger currentPage;
    NSInteger totalPage;
}
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@end

@implementation TheirWishListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    _dateFormatter = [[NSDateFormatter alloc] init];
    [_dateFormatter setDateFormat:@"MM/dd/yyyy"];
    currentPage = 1;
    totalPage = 1;
    
//    self.contactsList = @[@{@"name": @"Adobe",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"App Store",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Apple",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Cisco",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Facebook",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Google",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Google+",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Google Play",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"HP",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"iTunes",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"IBM",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Microsoft",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Objective-C",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Path",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Pinterest",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"RIMM",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Twitter",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Xcode",
//                            @"detail": @"Birthday, Location"},
//                          @{@"name": @"Yahoo",
//                            @"detail": @"Birthday, Location"},
//                          ];
//    
//    [self createAlphabetArray];
    if (_contactsList.count == 0) {
        [SharedAppDelegate startSpinner:@"Loading..."];
        self.dataManager = [DataManager updateFbFriend:self fbId:[UserDefaultHelper getFbId] fbToken:[FBSession activeSession].accessTokenData.accessToken userId:[UserDefaultHelper getUserId] appToken:[UserDefaultHelper getAppToken]];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [_searchResults count];
    } else {
        return [_contactsList count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"ContactCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.detailTextLabel.numberOfLines = 0;
    }
    
    FriendInfo *friend = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        friend = self.searchResults[indexPath.row];
    } else {
        friend = self.contactsList[indexPath.row];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", friend.firstName, friend.lastName];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@", [_dateFormatter stringFromDate:friend.birthday], friend.city];
    NSURL *url = [NSURL URLWithString:friend.profileImageUrl];
    [cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon_contact"]];
    
    return cell;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return _alphabetsArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    for (int i = 0; i< [_contactsList count]; i++) {
        // Here you return the name i.e. Honda,Mazda
        // and match the title for first letter of name
        // and move to that row corresponding to that indexpath as below
        FriendInfo *contact = _contactsList[i];
        NSString *letterString = [contact.firstName substringToIndex:1];
//        NSDictionary *contact = _contactsList[i];
//        NSString *letterString = [[contact objectForKey:@"name"] substringToIndex:1];
//        NSLog(@"letterString:%@", letterString);
        if ([letterString isEqualToString:title]) {
            [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            break;
        }
    }
    
    return index;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        [self performSegueWithIdentifier:@"TheirWishListDetails" sender:self];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == _contactsList.count - 1) {
        if (currentPage < totalPage) {
            currentPage++;
            [SharedAppDelegate startSpinner:@"Loading..."];
            self.dataManager = [DataManager getFriendsByUserId:self userId:[UserDefaultHelper getUserId] appToken:[UserDefaultHelper getAppToken] page:[NSNumber numberWithInt:currentPage]];
        }
    }
}

#pragma mark - Story board

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"TheirWishListDetails"]) {
        TheirWishListDetailsViewController *destViewController = segue.destinationViewController;
        
        NSIndexPath *indexPath = nil;
        FriendInfo *friend = nil;
        if ([self.searchDisplayController isActive]) {
            indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
//            destViewController.recipeName = [searchResults objectAtIndex:indexPath.row];
            friend = _searchResults[indexPath.row];
        } else {
            indexPath = [self.tableView indexPathForSelectedRow];
//            destViewController.recipeName = [recipes objectAtIndex:indexPath.row];
            friend = _contactsList[indexPath.row];
        }
        destViewController.friendInfo = friend;
    }
    
}

#pragma mark - Private methods

- (void)createAlphabetArray {
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < [_contactsList count]; i++) {
        FriendInfo *friend = _contactsList[i];
        if (friend.firstName.length > 0) {
            NSString *letterString = [friend.firstName substringToIndex:1];
            if (![mutableArray containsObject:letterString]) {
                [mutableArray addObject:letterString];
            }
        }
        
//        NSDictionary *contact = _contactsList[i];
//        NSString *letterString = [[contact objectForKey:@"name"] substringToIndex:1];
//        if (![mutableArray containsObject:letterString]) {
//            [mutableArray addObject:letterString];
//        }
    }
    self.alphabetsArray = mutableArray;
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSMutableArray *mutableArray = [NSMutableArray array];
    for (NSUInteger i = 0; i < _contactsList.count; i++) {
        FriendInfo *friend = _contactsList[i];
        NSString *name = [NSString stringWithFormat:@"%@ %@", friend.firstName, friend.lastName];
//        NSDictionary *contact = _contactsList[i];
//        NSString *name = contact[@"name"];
        name = [name lowercaseString];
        if ([name rangeOfString:searchText].location != NSNotFound) {
            [mutableArray addObject:friend];
        }
    }
    self.searchResults = [NSArray arrayWithArray:mutableArray];
}

#pragma mark - UISearchDisplayController delegate

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];
    
    return YES;
}

#pragma mark - DataManager delegate

- (void)dataManagerFinishGetData:(DataManager *)dataManager response:(id)response error:(NSError *)error
{
    [SharedAppDelegate stopSpinner];
    
    if (error) {
        NSLog(@"ERROR: %@", error.localizedDescription);
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:error.localizedDescription delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alertView show];
    } else {
        NSLog(@"%@", response);
        if ([dataManager.serviceName isEqualToString:[ServiceNameMapper updateFbFriend]]) {
            currentPage = 1;
            [SharedAppDelegate startSpinner:@"Loading..."];
            self.dataManager = [DataManager getFriendsByUserId:self userId:[UserDefaultHelper getUserId] appToken:[UserDefaultHelper getAppToken] page:[NSNumber numberWithInt:currentPage]];
        } else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper getFriendsByUserId]]) {
            FriendsByUserIdResult *result = response;
            totalPage = result.totalPages;
            if (currentPage == 1) {
                //initial
                self.contactsList = result.results;
            } else {
                //load more
                NSMutableArray *mutableArray = [NSMutableArray array];
                [mutableArray addObjectsFromArray:_contactsList];
                [mutableArray addObjectsFromArray:result.results];
                self.contactsList = [NSArray arrayWithArray:mutableArray];
            }
            
            self.contactsList = [self.contactsList sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                NSString *firstName1 = ((FriendInfo *)obj1).firstName;
                NSString *firstName2 = ((FriendInfo *)obj2).firstName;
                return [firstName1 compare:firstName2];
            }];
            
            [self createAlphabetArray];
            [_tableView reloadData];
        }
        
    }
}

@end
